package com.flashflexpro.tanksinbattle.battlescene {
import com.flashflexpro.tanksinbattle.battlescene.dto.BattleSceneObjectDto;

import flash.display.BitmapData;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;

public class BattleSceneObject extends MovieClip {
    
    private var _velocity:Point;
    private var _rotateVelocity:Number;

    public function get velocity():Point {
        return _velocity;
    }

    public function get rotateVelocity():Number {
        return _rotateVelocity;
    }

    protected var _battleSceneObjDto:BattleSceneObjectDto;

    public function BattleSceneObject( dto:BattleSceneObjectDto, scene:BattleScene ){
        _battleSceneObjDto = dto;
        _battleScene = scene;
        _velocity = new Point();
        _rotateVelocity = 0;
        x = dto.initialPosition.x;
        y = dto.initialPosition.y;
    }


    private var _battleScene:BattleScene;

    public function get battleScene():BattleScene {
        return _battleScene;
    }


    public function update( time:int ):void{

    }


    protected function checkIfCanMoveFromHit():Boolean {
        var canMove:Boolean = true;
        if (_hit != null) {
            var whereThisIsNow:Point = new Point(x, y);
            var whereHitIsNow:Point = new Point(_hit.x, _hit.y);
            //move it to see if still hit
            _hit.x += _hit.velocity.x;

            _hit.y += _hit.velocity.y;
            x += velocity.x;

            y += velocity.y;
            canMove = !_hit.hitTestObject(this);

            //move back
            this.x = whereThisIsNow.x;
            this.y = whereThisIsNow.y;

            _hit.x = whereHitIsNow.x;
            _hit.y = whereHitIsNow.y;
        }
        return true;
    }


    protected var _hit:BattleSceneObject;

    public function get battleSceneObjDto():BattleSceneObjectDto {
        return _battleSceneObjDto;
    }

    public function set battleSceneObjDto(value:BattleSceneObjectDto):void {
        _battleSceneObjDto = value;
    }

    public function get hit():BattleSceneObject {
        return _hit;
    }

    public function set hit(value:BattleSceneObject):void {
        _hit = value;
    }

    //todo:optimize this
    public function getHitBitMap():BitmapData{
        var hitWith:Sprite = hitArea!=null?hitArea:this;
        var rect:Rectangle = hitWith.getBounds(_battleScene);

        var ofset:Matrix = hitWith.transform.matrix;
        ofset.tx = hitWith.x - rect.x;
        ofset.ty = hitWith.y - rect.y;

        var bit:BitmapData = new BitmapData(rect.width, rect.height, true, 0);
        bit.draw(hitWith, ofset);
        return bit;
    }
}
}